package org.finalministry.gui;

import java.awt.Color;
import java.io.IOException;

import javax.swing.JFrame;
import javax.swing.WindowConstants;

import org.finalministry.database.FinalministryDatabase;
import org.finalministry.gui.components.FinalMinistryPanel;
import org.finalministry.gui.components.ImageButton;
import org.finalministry.gui.menu.GuiMainMenuCreator;

public class GuiMain extends JFrame {

	private static final long serialVersionUID = -5821216428592154799L;
	private FinalministryDatabase database;
	private GuiMainActionListener guiMainActionListener;
	private int lastNavigationImageY = 10;

	public GuiMain(FinalministryDatabase database) {
		this.database = database;
		init();

		this.setVisible(true);
	}

	private void init() {

		guiMainActionListener = new GuiMainActionListener(this);

		this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
		this.setBounds(0, 0, 1440, 900);
		this.setTitle("Finalministry Desktop Version 0.1");
		this.setBackground(Color.WHITE);

		// Write yourself a bette LayoutManager ... when there is enough time!
		// this.setLayout(null);

		// Add a Window Listener for the Closing Event
		addWindowClosingEventListener();

		// Add a menu
		addMenu();

		// Add a panel with JTree and a JDesktopPane
		add(new FinalMinistryPanel(this));
	}

	private void addNavigationIcons() throws IOException {
		addImageButton("Manage Congregations", "icons/group.png");
		addImageButton("Manage Preachers", "icons/user-male.png");
		addImageButton("Manage Territories", "icons/territory.png");
		addImageButton("Manage Contacts", "icons/contacts-icon.png");
		addImageButton("Statistics", "icons/statistics-icon.png");
	}

	private void addImageButton(String textOrActionCommand, String imagePath) throws IOException {
		ImageButton button = new ImageButton(textOrActionCommand, 80, lastNavigationImageY, 64, 64, imagePath, guiMainActionListener);
		this.add(button);
		this.add(button.getFLabel());

		lastNavigationImageY += 100;
	}

	private void addMenu() {

		GuiMainMenuCreator guiMainMenuCreator = new GuiMainMenuCreator(guiMainActionListener);

		this.setJMenuBar(guiMainMenuCreator.getMenuBar());
	}

	public void addWindowClosingEventListener() {
		addWindowListener(new java.awt.event.WindowAdapter() {
			@Override
			public void windowClosing(java.awt.event.WindowEvent windowEvent) {
				exit();
			}
		});
	}

	public void exit() {
		System.out.println("Closing Finalministry Desktop ... good bye!");
		database.stopServer();
		System.exit(0);
	}

}
